package com.ruoyi.kong.service.impl;

import com.ruoyi.kong.entity.KongEntity;
import com.ruoyi.kong.entity.KongTarget;
import com.ruoyi.kong.entity.KongUpstream;
import com.ruoyi.kong.entity.KongUpstreamVo;
import com.ruoyi.kong.fegin.KongClientService;
import com.ruoyi.kong.service.IKongUpstreamService;
import com.ruoyi.kong.utils.KongActiveProfileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

@Service
public class KongUpstreamServiceImpl implements IKongUpstreamService {


    @Autowired
    private KongActiveProfileUtil kongActiveProfileUtil;


    @Override
    public KongEntity<KongUpstream> upstreams() {
        KongEntity<KongUpstream> upstreams = KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).upstreams();
        if(!ObjectUtils.isEmpty(upstreams)){
            if(upstreams.getData().size()>0){
                for (KongUpstream kongUpstream : upstreams.getData()){
                    String upstreamId=kongUpstream.getId();
                    KongEntity<KongTarget> kongTargets = KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).targetsByUpstreamId(upstreamId);
                    kongUpstream.setKongTargets(kongTargets);
                }
            }
        }
        return  upstreams;
    }

    public KongEntity<KongTarget> targetsByUpstreamId(String upstreamId){
        return KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).targetsByUpstreamId(upstreamId);
    }

    public KongUpstream addUpstream(KongUpstreamVo kongUpstream){
        return KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).addUpstream(kongUpstream);
    }

    public KongUpstream updateUpstream(String upstreamId, KongUpstreamVo kongUpstream){
        return KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).updateUpstream(upstreamId,kongUpstream);
    }

    public void deleteUpstream(String upstreamId){
        KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).deleteUpstream(upstreamId);
    }

    public KongUpstream upstreamsById(String id){
        return KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).upstreamsById(id);
    }

    public KongTarget addTarget(String upstreamId,KongTarget target){
        return KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).addTarget(upstreamId,target);
    }

    public KongTarget deleteTarget(String upstreamId,String id){
        return KongClientService.getInstance(kongActiveProfileUtil.getKongServerUrl()).deleteTarget(upstreamId,id);
    }
}
